package handle

import (
	"github.com/martini-contrib/render"
	"net/http"
	"strconv"
)

func IsCp(r render.Render, req *http.Request) {
	var err error
	req.ParseForm()
	toUser := req.PostFormValue("toUser")
	if toUser == "" {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": "param is not enough",
		})
		return
	}
	var userid = req.Header.Get("userid")
	Fid, err := strconv.Atoi(userid)
	if err != nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": err.Error(),
		})
		return
	}
	toMemberInfo, err := memberModel.FindOne(toUser)
	if err != nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": err.Error(),
		})
		return
	}

	is, err := relationModel.IsCp(toMemberInfo.Id, int64(Fid))
	if err != nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": err.Error(),
		})
		return
	}
	if !is {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": "",
		})
		return
	}
	r.JSON(200, map[string]interface{}{
		"code": "0",
		"info": "",
	})
	return
}
func SetCpHandle(r render.Render, req *http.Request) {
	var err error
	var userid = req.Header.Get("userid")
	Fid, err := strconv.Atoi(userid)
	if err != nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": err.Error(),
		})
		return
	}
	req.ParseForm()
	var cp = req.PostFormValue("cp")
	if cp == "" {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": "param is not enough",
		})
		return
	}
	cpInfo, err := memberModel.FindOne(cp)
	if err != nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": err.Error(),
		})
		return
	}
	if cpInfo == nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": "the cp is not exist",
		})
		return
	}
	err = relationModel.Cp(int64(Fid), cpInfo.Id)
	if err != nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": err.Error(),
		})
		return
	}
	r.JSON(200, map[string]interface{}{
		"code":    "0",
		"info":    "",
		"cp_name": cpInfo.Name,
		"cp_id":   cpInfo.Id,
	})
	return
}
func GetCpHandle(r render.Render, req *http.Request) {
	var err error
	var userid = req.Header.Get("userid")
	Fid, err := strconv.Atoi(userid)
	if err != nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": err.Error(),
		})
		return
	}
	cpInfo, err := relationModel.FindCp(int64(Fid))
	if err != nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": err.Error(),
		})
		return
	}
	if cpInfo == nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": "the cp is not exist",
		})
		return
	}
	r.JSON(200, map[string]interface{}{
		"code":    "0",
		"info":    "",
		"cp_name": cpInfo.Name,
		"cp_id":   cpInfo.Id,
	})
	return
}
